//
//  MainViewController.swift
//  02-weibo（swift第二遍）
//
//  Created by 刘涛 on 15/6/23.
//  Copyright © 2015年 tao6. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        // 这样就可以将自定义的tabBar替换为系统tabBar（KVC 大招），因为系统tabBar是只读的。
        
        let tb = MainTabBar()
        
        setValue(tb, forKey: "tabBar")
        
        
        tb.composeButton.addTarget(self, action: "compostButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        
        
        addChildViewControllers()
        
        
    }
    
    // 点击撰写按钮，按钮监听方法不能私有
    func compostButtonClicked() {
        print(__FUNCTION__)
    }
    
    
    
    private func addChildViewControllers() {

        
        
        let path = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil)!
        
        let data = NSData(contentsOfFile: path)!
        
        do {
            let array = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
            
            for dict in array as! [[String: String]]  {
                addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!)
            }
        } catch {
            // 捕获异常
            print(error)
            
            addChildViewController("HomeTableViewController", title: "首页", imageName: "tabbar_home")
            addChildViewController("MessageTableViewController", title: "消息", imageName: "tabbar_message_center")
            addChildViewController("DiscoverTableViewController", title: "发现", imageName: "tabbar_discover")
            addChildViewController("ProfileTableViewController", title: "我", imageName: "tabbar_profile")
        }
    }
    
    
    
    
    private func addChildViewController(vcName: String, title: String, imageName: String) {
        // 设置 tintColor
//        tabBar.tintColor = UIColor.orangeColor()
        
        // 在 swift 中，类名是包含命名空间的
        // 命名空间默认是项目名称，同一个命名空间全局共享
        // 0. info.plist 的信息
        // 在 swift 开发中，通常设定对象的类型，写在右侧 `as! String` `as? String`
        // 都是自动推导，右侧指定好，左侧变量类型自然OK
        let ns = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
        
        // 1. 将字符串转换成类
        print(ns + "." + vcName)
        let cls: AnyClass = NSClassFromString(ns + "." + vcName)!
        
        // 2. 实例化对象
        let vc = cls.alloc() as! UIViewController
        print(vc)
        
        // 从内向外设置，nav & tabbar 都有标题
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted")
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
    


    



}
